<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="./js/jquery-2.1.1.min.js"></script>
  <title>Document</title>
</head>
<body>
  <h1>微信公众号获取unionId</h1>
  <hr>

  <script>
    const config = {
      appID: 'wx3680aee5b396cc0f',
      appsecret: '626c988a2e4af8cc459424187951792e',
      REDIRECT_URI: 'http://b8k36i.natappfree.cc/html/',
    }

    // 获取url的参数
    function getQueryString() {
        let str = window.location.search
        console.log('str', str);
        // ?code=051YCH000vmCDN1EmM200Bdl0f3YCH0w:77 str ?
        if (str && str.includes("?") && str.includes("=")) {
            let obj = {}
            str = str.slice(1)
            if (str.includes("&")) {
                let arr = str.split("&")
                for (let i = 0; i < arr.length; i++) {
                    let one = arr[i].split("=")
                    obj[one[0]] = one[1]
                }
            } else {
                let one = str.split("=")
                obj[one[0]] = one[1]
            }
            return obj;
        }
    }

    // 获取access_token和openid
    var resData = getQueryString("code");
    console.log('resData', resData);
    
    // 1.第一次没有code时，应该去获取code
    if(!resData){
      // 获取用户授权
      var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appID}&redirect_uri=${config.REDIRECT_URI}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
      window.location.href = url;
    } else {
      var {code} = resData;
      // 2.传给后台-让后台访问，否则跨域
      $.get('/getUnionId?code='+code, function(data) {
          console.log('res-data', data);
      });
  
    }
    </script>
</body>
</html>